<template>
  <div class="container">
    <template v-if="!getCustomerId">
      <get-user-info v-if="isGetUserInfo" @authPhoneInfo="authPhoneInfo"></get-user-info>
      <get-phone-info v-if="isGetPhoneInfo"></get-phone-info>
    </template>
    <template v-if="getCustomerId && !getPhone">
      <get-phone-info v-if="isGetPhoneInfo"></get-phone-info>
    </template>
    <div class="cover-bar">
      <video id="myVideo"
        v-if="liveData.introduceVideo"
        :src="liveData.introduceVideo"
      >
        <cover-view class="height-245" v-if="videoNoShow">
          <cover-image :src="liveData.shareImg" class="cover-img" mode="widthFix" />
          <cover-view class="cover-play flex flex-center">
            <cover-image :src="fileSpace + '/images/play-icon.png'" class="width-58 height-58" mode="widthFix" @click="playVideo" />
          </cover-view>
        </cover-view>
      </video>
      <img :src="liveData.shareImg" class="cover-img" mode="widthFix" v-else/>
    </div>
    <div class="warp">
      <div class="main">
        <div class="flex v-align-c title">
          <span class="flex-item font-13">分享文案</span>
          <label class="font-12" @click="$pt.setClipboardData({data: liveData.shareCopy || ''})">复制</label>
        </div>
        <div class="content font-14 font-color-6">
          <div class="desc">{{ liveData.shareCopy }}</div>
        </div>
      </div>
      <ul class="flex footer-bar text-align-c">
        <li class="flex-item pos-rel">
          <button open-type="share" class="share-btn"></button>
          <div class="flex flex-center">
            <span>
              <img v-if="fileSpace" :src="fileSpace + '/images/icon-share-wx-2.png'" alt="" class="width-71 height-71">
              <i class="font-13">分享好友</i>
            </span>
          </div>
        </li>
        <li class="flex-item" @click="createPoster">
          <div class="flex flex-center">
            <span>
              <img v-if="fileSpace" :src="fileSpace + '/images/icon-share-p-2.png'" alt="" class="width-71 height-71">
              <i class="font-13">下载海报</i>
            </span>
          </div>
        </li>
        <li class="flex-item" @click="liveTo">
          <div class="flex flex-center">
            <span>
              <img v-if="fileSpace" :src="fileSpace + '/images/icon-share-l-2.gif'" alt="" class="width-71 height-71">
              <i class="font-13">进入直播间</i>
            </span>
          </div>
        </li>
        <li v-if="!getCustomerId || !getPhone" style="position:absolute;top:0;left:0;width:66%;height:100%;z-index:1001;" @click="userInfo"></li>
      </ul>
    </div>
    <div class="div-pop" v-if="isCreatePoster" @click="isCreatePoster=false" catchtouchmove="true">      
      <div class="create-poster">
        <cover-view class="share-close" @click="isCreatePoster=false">
          <cover-image v-if="fileSpace" class="width-34 height-34"
              :src="fileSpace + '/images/share-layer-close-2.png'"/>
        </cover-view>
        <canvas canvas-id="shareCanvas" class="share-canvas"></canvas>
      </div>
      <div class="save-img">
        <button size="default" class="primary-button"
          @click="saveToAlbum('shareCanvas')">保存</button>
      </div>
    </div>
  </div>
</template>

<script>
  import { getLiveRoom, addLiveRoomVeekrayWxaCode, liveRoomLogSave } from '@/api/home'
  import GetUserInfo from '@/components/GetUserInfo'
  import GetPhoneInfo from '@/components/GetPhoneInfo'
  export default {
    data() {
      return {
        liveData: {},
        roomid: '',
        isCreatePoster: false,
        memberInfo: {},
        goods: {},
        imgInfo: {},
        codeInfo: {},
        shareMemberId: '',
        shareType: null,
        memberId: '',
        videoNoShow: true,
        live_status: null,
        isGetUserInfo: false,
        isGetPhoneInfo: false
      }
    },
    components: {GetUserInfo, GetPhoneInfo},
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
    },
    onShow() {
      this.shareMemberId = this.getCurrentPage().query.shareMemberId
      this.shareType = Number(this.getCurrentPage().query.shareType)
      this.roomid = Number(this.getCurrentPage().query.roomid)
      this.memberId = this.getCurrentPage().query.memberId
      this.live_status = this.getCurrentPage().query.live_status
      // console.log(this.shareMemberId)
      // console.log(this.shareType)
      // console.log(this.roomid)
      // console.log(this.memberId)
      // this.roomid = 62
      let liveShare = {}
      liveShare = {
        shareMemberId: this.shareMemberId,
        shareType: this.shareType,
        roomid: this.roomid,
        memberId: this.memberId
      }
      if (this.shareMemberId && this.roomid) {
        this.$pt.setStorageSync('liveShare', liveShare)
        this.$pt.removeStorageSync('scanCode')
        this.$pt.removeStorageSync('scanIn')
      }
      this.getLiveRoom()
      this.addLiveRoomVeekrayWxaCode()
      if (this.shareMemberId) {
        this.liveRoomLogSave()
      }
    },
    onShareAppMessage() {
      this.$pt.setStorageSync('chooseLocation', true)
      return {
        title: this.liveData.roomName,
        imageUrl: this.liveData.shareImg,
        path: 'pages/home/live-share/main?shareMemberId=' + this.getCustomerId + '&shareType=0&roomid=' + this.roomid + '&memberId=' + this.getMemberId
      }
    },
    methods: {
      // 用户授权
      userInfo() {
        if (!this.getCustomerId) {
          this.isGetUserInfo = true
        } else if (!this.getPhone) {
          this.isGetPhoneInfo = true
        }
      },
      authPhoneInfo() {
        this.isGetPhoneInfo = true
      },
      playVideo() {
        // 将在此处判断店播是否上传视频、直播是否开始
        if (this.live_status === 101) {
          // 如果正在直播，进入直播间
          return this.liveTo()
        }
        this.videoNoShow = false
        let videoContent = this.$pt.createVideoContext('myVideo')
        videoContent.play()
      },
      liveTo() {
        let customParams = {
          liveShareMemberId: this.getMemberId,
          liveShareCustomerId: this.getCustomerId
        }
        this.$pt.navigateTo({
          url: 'plugin-private://' + process.env.LIVE_ID + '/pages/live-player-plugin?room_id=' + this.roomid +
           '&custom_params=' + encodeURIComponent(JSON.stringify(customParams))
        })
      },
      liveRoomLogSave() {
        let data = {
          roomId: this.roomid,
          memberId: this.getMemberId,
          customerMemberId: this.getCustomerId,
          shareMemberId: this.shareMemberId,
          shareType: this.shareType
        }
        liveRoomLogSave(data).then((response) => {
          if (response.isError) return
          this.codeInfo = response.data
        }).catch(() => {
        })
      },
      addLiveRoomVeekrayWxaCode() {
        addLiveRoomVeekrayWxaCode({
          roomId: this.roomid,
          shareMemberId: this.getMemberId
        }).then((response) => {
          if (response.isError) return
          this.codeInfo = response.data
        }).catch(() => {
        })
      },
      getLiveRoom() {
        if (!this.getMemberId) return
        this.$utils.showToast({
          title: '加载中',
          icon: 'loading'
        })
        getLiveRoom({
          roomid: this.roomid,
          memberId: this.getMemberId
        }).then((response) => {
          if (response.isError) return
          this.$pt.hideToast()
          this.liveData = response.data
          if (!Object.keys(this.liveData).length) {
            this.$utils.showToast({
              title: '该直播数据为空，请稍后再试！',
              duration: 5000
            })
            return
          }
          // this.liveData.shareCopy = '青蛙王子婴儿倍护润唇膏'
          // this.liveData.shareCopy = '青蛙王子婴儿倍护润唇膏，青蛙王子婴儿倍护润唇膏，青蛙王子婴儿倍护润唇膏，青蛙王子婴儿倍护润唇膏，青蛙王子婴儿倍护润唇膏，青蛙王子婴儿倍护润唇膏'
          // this.liveData.shareImg = 'http://mmbiz.qpic.cn/mmbiz_jpg/JHpPv9CkxtsMu5oUYkEFiaiaLJ2FqKdfjB5ibmWZicgiayq8lv6oxfWlsnbqsWicYBlIaldwSWoZtkiblE33QQaPNq1Qg/0'
          // this.liveData.shareImg = 'http://mmbiz.qpic.cn/mmbiz_jpg/JHpPv9CkxtsMu5oUYkEFiaiaLJ2FqKdfjBhkZocRCUb0ibLOwySYzh1OpfhWJ3FbZibdYBIIvS7MCbtqDcuFGjDHLw/0'
          // this.liveData.shareImg = 'http://mmbiz.qpic.cn/mmbiz_jpg/JHpPv9CkxtsMu5oUYkEFiaiaLJ2FqKdfjBJ1oQVoHKbBxTkqrbgJtchVaOtn2AMzuTPibTK3l5Do7fGmfVibLQWrEA/0'
          // this.liveData.shareImg = 'https://veekrayimg.joinsun.vip/images/share-over-bg-4.png'
          const that = this
          this.$pt.getImageInfo({
            src: that.liveData.shareImg,
            success(res) {
              that.imgInfo = {
                width: res.width,
                height: res.height
              }
            },
            fail: function(res) {
              that.imgInfo = {
                width: 250,
                height: 200
              }
            }
          })
        }).catch(() => {
        })
      },
      createPoster() {
        this.isCreatePoster = true
        this.drawPage()
      },
      roundRectColor(context, x, y, w, h, r) {
        // 绘制圆角矩形（纯色填充）
        context.save()
        context.fillStyle = '#ffffff'
        context.strokeStyle = '#ffffff'
        context.lineJoin = 'round' // 交点设置成圆角
        context.lineWidth = r
        context.strokeRect(x + r / 2, y + r / 2, w - r, h - r)
        context.fillRect(x + r, y + r, w - r * 2, h - r * 2)
        context.stroke()
        context.closePath()
      },
      drawPage() {
        const that = this
        let shareImgWidth = null
        let shareImgHeight = null
        if (that.imgInfo.width) {
          shareImgWidth = that.imgInfo.width
          shareImgHeight = (that.imgInfo.width * 200) / 250
          if (that.imgInfo.width / that.imgInfo.height > shareImgWidth / shareImgHeight) {
            shareImgWidth = shareImgWidth * (250 / that.imgInfo.width) / 0.7
            shareImgHeight = shareImgHeight * (250 / that.imgInfo.width) / 0.7
          } else {
            shareImgWidth = shareImgWidth * 0.9
            shareImgHeight = shareImgHeight * 0.9
          }
        }
        let platIOS = false
        if (that.$pt.getSystemInfoSync().system.indexOf('iOS') !== -1) {
          platIOS = true
        }
        let rpx = that.$pt.getSystemInfoSync().windowWidth / 375
        that.$utils.showToast({
          title: '图片生成中',
          icon: 'loading',
          duration: 1000
        })
        const context = that.$pt.createCanvasContext('shareCanvas')
        // 清除画布，防止层叠
        context.clearRect(0, 0, 290 * rpx, 468 * rpx)
        // 背景黄色
        context.setFillStyle('#fee100')
        context.fillRect(0, 0, 290 * rpx, 468 * rpx)
        // 背景白色
        that.roundRectColor(context, 15 * rpx, 18 * rpx, 260 * rpx, 290 * rpx, 16 * rpx)
        // 产品图
        that.$pt.downloadFile({
          url: that.liveData.shareImg,
          success: function(img) {
            context.drawImage(img.tempFilePath, 0 * rpx, 0 * rpx, shareImgWidth * rpx, shareImgHeight * rpx, 20 * rpx, 23 * rpx, 250 * rpx, 200 * rpx)
            context.draw(true)
          }
        })
        // 切割字符 展示最多两行商品标题
        if (that.liveData.roomName) {
          context.setFillStyle('#333333')
          if (platIOS) {
            that.dealWords({
              ctx: context,
              fontSize: 15, // 字体大小
              font: 'normal bold 15', // 字体大小
              word: that.liveData.roomName, // 需要处理的文字
              maxWidth: 230 * rpx, // 一行文字最大宽度
              x: 31 * rpx, // 文字在x轴要显示的位置
              y: 237 * rpx, // 文字在y轴要显示的位置
              maxLine: 2 // 文字最多显示的行数
            })
          } else {
            that.dealWords({
              ctx: context,
              fontSize: 15, // 字体大小
              font: 'normal bold  15', // 字体大小
              word: that.liveData.roomName, // 需要处理的文字
              maxWidth: 230 * rpx, // 一行文字最大宽度
              x: 31 * rpx, // 文字在x轴要显示的位置
              y: 237 * rpx, // 文字在y轴要显示的位置
              maxLine: 2 // 文字最多显示的行数
            })
          }
        }
        // 扫码查看图片
        that.$pt.downloadFile({
          url: that.fileSpace + '/images/share-point-l-4.png',
          success: function(wxaCode) {
            context.drawImage(wxaCode.tempFilePath, 20 * rpx, 232 * rpx, 26 * rpx, 22 * rpx)
            context.draw(true)
          }
        })
        that.$pt.downloadFile({
          url: that.fileSpace + '/images/share-point-r.png',
          success: function(wxaCode) {
            context.drawImage(wxaCode.tempFilePath, 245 * rpx, 267 * rpx, 26 * rpx, 22 * rpx)
            context.draw(true)
          }
        })
        // 背景白色
        that.roundRectColor(context, 15 * rpx, 322 * rpx, 260 * rpx, 93 * rpx, 16 * rpx)
        // 商品价格
        if (that.liveData.price) {
          context.setFillStyle('#ff0000')
          context.setFontSize(20)
          context.fillText('最低' + that.liveData.price + '元', 33 * rpx, 364 * rpx)
        }
        // 商品件数
        if (that.liveData.goodsNum) {
          context.setFillStyle('#999999')
          context.setFontSize(13)
          context.fillText('共' + that.liveData.goodsNum + '件商品', 33 * rpx, 387 * rpx)
        }
        // 二维码
        if (that.codeInfo.shareCode) {
          that.$pt.downloadFile({
            url: that.codeInfo.shareCode,
            success: function(wxaCode) {
              context.drawImage(wxaCode.tempFilePath, 193 * rpx, 331 * rpx, 55 * rpx, 55 * rpx)
              context.draw(true)
            }
          })
        }
        // 扫码查看图片
        that.$pt.downloadFile({
          url: that.fileSpace + '/images/share-pic-2.png',
          success: function(wxaCode) {
            context.drawImage(wxaCode.tempFilePath, 192 * rpx, 392 * rpx, 64 * rpx, 15 * rpx)
            context.draw(true)
          }
        })
      },
      dealWords(options) {
        // 处理文字多出省略号显示
        options.ctx.setFontSize(options.fontSize) // 设置字体大小
        // options.ctx.font = options.font
        var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth) // 实际总共能分多少行
        var count = allRow >= options.maxLine ? options.maxLine : allRow // 实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
        var endPos = 0 // 当前字符串的截断点
        let lineNum = 0
        for (var j = 0; j < count; j++) {
          var nowStr = options.word.slice(endPos) // 当前剩余的字符串
          var rowWid = 0 // 每一行当前宽度
          if (options.ctx.measureText(nowStr).width > options.maxWidth) { // 如果当前的字符串宽度大于最大宽度，然后开始截取
            lineNum = lineNum + 1
            for (var m = 0; m < nowStr.length; m++) {
              rowWid += options.ctx.measureText(nowStr[m]).width // 当前字符串总宽度
              if (rowWid > options.maxWidth) {
                if (j === options.maxLine - 1) { // 如果是最后一行
                  options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 21) // (j+1)*18这是每一行的高度
                } else {
                  options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 21)
                }
                endPos += m // 下次截断点
                break
              }
            }
          } else { // 如果当前的字符串宽度小于最大宽度就直接输出
            if (lineNum > 0) {
              options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 21)
              return
            }
            options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 21)
          }
        }
      },
      saveToAlbum: function(canvasId) {
        const that = this
        that.$pt.canvasToTempFilePath({
          canvasId: canvasId,
          success: (res) => {
            const filePath = res.tempFilePath
            if (filePath) {
              that.$pt.saveImageToPhotosAlbum({
                filePath: filePath,
                success: (res) => {
                  that.$utils.showToast({ title: '保存成功，请到手机相册查看' })
                },
                fail: function(err) {
                  if (err.errMsg.indexOf('cancel') !== -1) return
                  that.$pt.showModal({
                    content: '保存图片需要访问你的相册',
                    success(res) {
                      if (res.confirm) {
                        that.$pt.openSetting()
                      } else if (res.cancel) {
                        console.log(err)
                      }
                    }
                  })
                }
              })
            }
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .container{
    background: #fff;
    .cover-bar{
      width: 100%;
      height: 245px;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 5;
      overflow: hidden;
    }
    .cover-img{
      width: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 4;
      height: unset;
    }
    #myVideo{
      width: 100%;
      height: 245px;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 4;
      .cover-play{
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 245px;
        z-index: 5;
        background-color: rgba(0, 0, 0, .5);
      }
    }
    .warp{
      position: relative;
      z-index: 10;
      background: #fff;
      margin-top: 245px;
    }
    .share-btn {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      background: none;
    }
    .share-btn:after {
      border: none;
    }
    .create-poster {
      background-color: #fff;
      width: 290px;
      height: 468px;
      margin-top: -50px;
      position: relative;
      .share-close{
        position: absolute;
        right: 0;
        top: -1px;
        z-index: 100;
      }
    }
    .share-canvas {
      width: 290px;
      height: 468px;
      background-color: #fff;
    }
    .save-img{
      position: fixed;
      bottom: 20px;
      left: 0;
      width: 100%;
      height: 45px;
      text-align: center;
      button{
        display: inline-block;
        width: 165px;
        height: 45px;
        line-height: 45px;
        border-radius: 100px;
        padding: unset;
        color: #333;
        font-size: 18px;
        font-weight: bold;
        background-color: #ffe103;
      }
    }    
    .main{
      margin: 15px 15px;
      .title{
        padding: 10px 0;
        label{
          border:1px solid #999699;
          border-radius:3px;
          padding: 0 7px;
        }        
      }
      .content{
        background: #f4f7f4;
        border-radius: 8px;
        padding: 10px;        
        .desc{
          height: 130px;
          overflow-x: hidden;
          overflow-y: scroll;
        }
      }
    }
    .footer-bar{
      border-top: #f9fcf8 15px solid;
      padding: 27px 0;
      position: relative;
    }
  }  
</style>
